package com.travelzen._21.concurrent;

public class TestVolatile {
	static volatile int count = 0;
	static volatile boolean flag;

	static void set(boolean t) {
		flag = t;
	}

	static void inc() throws InterruptedException {
		Thread.sleep(1);
		count++;
	}

	public static void main(String[] args) throws InterruptedException {

		for (int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						TestVolatile.inc();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					System.out.println(flag);
					if (flag) {
						System.out.println("flag has changed!!!");
						break;
					}
				}

			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				set(true);
			}
		}).start();

		System.out.println(TestVolatile.count + "__________");
	}
}
